import base64
import sys
import datetime
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QScrollArea, QFrame, QHBoxLayout, QRadioButton, \
    QPushButton, QLabel, QLineEdit, QGridLayout, QMessageBox, QTextEdit
from PyQt5.QtCore import Qt
from func import view
from config import button_config, input_config, frame_config,Text_config
from my_ import My
from menu_seller import Menu1 as Seller_menu
from history_order import His_order
from show_comment import ShopComment

class Menu1(QWidget):
    def __init__(self,parent=None):
        super().__init__()

        self.parent = parent
        self.client=self.parent.client
        self.user_name=self.client.username
        self.password=self.parent.client.password
        self.is_admin=self.parent.client.is_admin
        # self.user_name='dio'
        # self.password='00000000'
        # self.is_admin=0
        self.client.add_online(self.user_name)
        self.sf='client'


        parser={
            'user_name':self.user_name,
        }
        data=self.client.get_user(parser).get('data')
        self.user_id=data.get('user_id')
        self.email=data.get('email')
        self.avatar=base64.b64decode(data.get('avatar'))
        self.setWindowTitle("购物商场")
        self.resize(600, 800)
        self.setStyleSheet("background-color: rgb(255, 255, 255);")
        mainLayout = QVBoxLayout(self)
        mainLayout.setContentsMargins(0,0,0,0)
        self.initUI(mainLayout)
    def initUI(self,mainLayout):
        #界面导航栏
        layout=QHBoxLayout()
        mainLayout.addLayout(layout)
        self.create_navi_search(layout)
        layout1=QHBoxLayout()
        mainLayout.addLayout(layout1)
        self.create_navi_btn(layout1)

        scroll_area = QScrollArea()
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setWidgetResizable(True)
        self.menu_frame = QFrame()
        self.menu_frame.setStyleSheet(frame_config.frame_style4)
        scroll_area.setWidget(self.menu_frame)
        mainLayout.addWidget(scroll_area)
        layout = QGridLayout(self.menu_frame)
        layout.setColumnStretch(0, 1)
        layout.setColumnStretch(1, 1)
        layout.setColumnStretch(2, 1)
        parser={
            'mode' : 1,
            'user_name':self.user_name,
            'category':'时尚女装👠'
        }
        shops=self.client.get_shops(parser).get('data')
        self.insert_shop(layout,shops)
        parser={
            'user_id':self.user_id,
        }
        mes_ad=self.client.exit_admin_mes(parser)
        for i in mes_ad:
            text=f'({i[1]}):{i[2]}'
            QMessageBox.information(None,'一条来自管理员的信息',text)
            parser={
                'mes_id':i[0],
            }
            self.client.delete_chat(parser)


    def create_navi_search(self,layout):
        logo = QLabel()
        img=QPixmap('../static/img/logo.png')
        img = img.scaled(100, 100, Qt.KeepAspectRatio)
        logo.setPixmap(img)
        layout.addWidget(logo)
        self.search_input=QLineEdit()
        self.search_input.setStyleSheet(input_config.input_style5)
        self.search_input.setPlaceholderText("请输入您要搜索的商品名或品牌")
        layout.addWidget(self.search_input)
        search_btn=QPushButton('🔍')
        search_btn.setStyleSheet(button_config.button_style6)
        search_btn.setFixedSize(60,60)
        layout.addWidget(search_btn)
        search_btn.clicked.connect(self.search_btn_clicked)


        shop_car=QPushButton('🛒')
        shop_car.setStyleSheet(button_config.button_style6)
        shop_car.setFixedSize(60,60)
        layout.addWidget(shop_car)

        self.my_btn=QPushButton('🙂')
        self.my_btn.setStyleSheet(button_config.button_style6)
        self.my_btn.setFixedSize(60,60)
        layout.addWidget(self.my_btn)
        text=f'当前账户{self.user_name}'
        self.my_btn.setToolTip(text)
        shop_car.clicked.connect(self.on_shop_car_clicked)
        self.my_btn.clicked.connect(self.my_btn_clicked)


    def create_navi_btn(self,layout):
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        text_list=['时尚女装👠','运动男装👟','数码产品📱','休闲零食🍿','儿童玩具🧸','医疗健康💊','办公文具💼','化妆产品💄','材米油盐🍚','实用工具🔨']
        for text in text_list:
            button=QPushButton(text)
            button.setStyleSheet(button_config.button_style5)
            button.setFixedHeight(30)
            layout.addWidget(button)
            button.clicked.connect(self.select_category)
    def insert_shop(self,layout,shops):
        count=0
        for shop in shops:
            shop_name=shop['shop_name']
            seller_name=shop['sellername']
            price=shop['price']
            brand=shop['brand']
            category=shop['category']
            description=shop['description']
            avatar = base64.b64decode(shop.get('avatar'))
            frame=QFrame()
            frame.setFixedHeight(300)
            frame.setStyleSheet(frame_config.frame_style1)
            layout.addWidget(frame,count//3,count%3)
            count+=1
            layout1=QVBoxLayout(frame)

            text=QLabel(shop_name)
            text.setStyleSheet(Text_config.text_style2)
            layout1.addWidget(text)

            img_label=QLabel()
            img = QPixmap()
            img.loadFromData(avatar)
            img = img.scaled(120, 120, Qt.KeepAspectRatio)
            img_label.setPixmap(img)
            img_label.setAlignment(Qt.AlignCenter)
            layout1.addWidget(img_label)
            text=QLabel(str(price))
            text.setStyleSheet(Text_config.text_style2)
            layout1.addWidget(text)


            layout2=QHBoxLayout()
            layout1.addLayout(layout2)
            btn_sub=QPushButton()
            btn_sub.setText('-')
            btn_sub.setFixedSize(20,30)
            num=QTextEdit()
            num.setReadOnly(True)
            num.setText('0')
            num.setFixedSize(20,30)
            btn_add=QPushButton()
            btn_add.setText('+')
            btn_add.setFixedSize(20,30)
            btn_sub.setProperty('input',num)
            btn_add.setProperty('input',num)
            layout2.addWidget(btn_sub)
            layout2.addWidget(num)
            layout2.addWidget(btn_add)

            btn_sub.clicked.connect(self.sub_num_clicked)
            btn_add.clicked.connect(self.add_num_clicked)


            buy_btn=QPushButton('购买')
            buy_btn.setStyleSheet(button_config.button_style1)
            buy_btn.setFixedHeight(30)
            layout2.addWidget(buy_btn)
            buy_btn.setProperty('input',num)
            buy_btn.setProperty("sellername", shop.get('sellername'))
            buy_btn.setProperty("shop_name", shop.get('shop_name'))
            buy_btn.setProperty("shop_id", shop.get('ID'))

            com_btn=QPushButton('查看评论')
            com_btn.setStyleSheet(button_config.button_style1)
            com_btn.setFixedHeight(30)
            layout2.addWidget(com_btn)
            com_btn.setProperty("shop_name", shop.get('shop_name'))
            com_btn.setProperty("shop_id", shop.get('ID'))


            text=f"卖家：{seller_name}，品牌{brand}，商品详情：{description}"
            frame.setToolTip(text)
            buy_btn.clicked.connect(self.buy_btn_clicked)
            com_btn.clicked.connect(self.com_btn_clicked)


    def my_btn_clicked(self):
        my = My(self)
        my.exec_()
        text=f'当前账户{self.user_name}'
        self.my_btn.setToolTip(text)
        if self.sf=='seller':
            self.window=Seller_menu(self)
            self.window.show()
            self.close()
    def select_category(self):
        sender=self.sender()
        text=sender.text()
        parser={
            'mode' :1,
            'category':text,
            'user_name':self.user_name,
        }
        shops=self.client.get_shops(parser).get('data')
        view.clear_layout(self.menu_frame.layout())
        layout = self.menu_frame.layout()
        if layout is None:  # 如果没有布局则新建
            layout = QGridLayout(self.menu_frame)
            layout.setColumnStretch(0, 1)
            layout.setColumnStretch(1, 1)
            layout.setColumnStretch(2, 1)
        self.insert_shop(layout,shops)
    #模糊查询商品
    def search_btn_clicked(self):
        text=self.search_input.text()
        parser={
            'information':text,
            'user_id':self.user_id,
            'mode':1
        }
        res=self.client.fuzzy_select_shop(parser)
        if res.get('code')==400:
            QMessageBox.information(None,'提示',res.get('msg'))
            return
        shops=res.get('data')
        view.clear_layout(self.menu_frame.layout())
        layout = self.menu_frame.layout()
        if layout is None:  # 如果没有布局则新建
            layout = QGridLayout(self.menu_frame)
            layout.setColumnStretch(0, 1)
            layout.setColumnStretch(1, 1)
            layout.setColumnStretch(2, 1)
        self.insert_shop(layout,shops)
    #点击购买按钮
    def buy_btn_clicked(self):
        sender=self.sender()
        seller_name=sender.property('sellername')
        shop_name=sender.property('shop_name')
        shop_id=sender.property('shop_id')
        input_num=sender.property('input')
        num=int(input_num.toPlainText())
        if num==0:
            QMessageBox.critical(None,'错误','购买数量不能为0')
            return
        parser={
            'date' : datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'quantity' : num,
            'shop_id' : shop_id,
            'user_id':self.user_id
        }
        dic=self.client.add_orders(parser)
        if dic['code']==200:
            QMessageBox.information(None,'提示',dic['msg'])
        else:
            QMessageBox.critical(None,'错误',dic['msg'])

    #查看评论
    def com_btn_clicked(self):
        sender=self.sender()
        self.shop_name=sender.property('shop_name')
        self.shop_id=sender.property('shop_id')
        com = ShopComment(self)
        com.exec_()
    #查看历史订单
    def on_shop_car_clicked(self):
        parser={
            'user_id':self.user_id,
        }
        print(parser)
        his_or=His_order(self)
        res =his_or.exec_()

    #减少数量
    def sub_num_clicked(self):
        sender=self.sender()
        input=sender.property('input')
        num=int(input.toPlainText())-1
        if num>=0:
            input.setText(str(num))

    # z增加数量
    def add_num_clicked(self):
        sender = self.sender()
        input = sender.property('input')
        num = int(input.toPlainText()) + 1
        input.setText(str(num))

    def closeEvent(self,event):
        self.client.logout(self.user_name)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window=Menu1()
    window.show()
    sys.exit(app.exec_())
